﻿using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MyWeb.IOC.Common
{
    public sealed class RegisterTypes
    {
        public static void Register(IUnityContainer container, string assemblyName)
        {
            Register(container, Assembly.Load(assemblyName));
        }

        public static void Register(IUnityContainer container, Assembly assembly)
        {
            Registers(container, new Assembly[] { assembly });
        }

        public static void Registers(IUnityContainer container, IEnumerable<Assembly> assemblys)
        {
            Dictionary<Type, Type> types = new Dictionary<Type, Type>();

            var list = assemblys.ToList();

            foreach (var assembly in list)
            {
                Assembly[] appDomains = AppDomain.CurrentDomain.GetAssemblies();
                if (appDomains != null)
                {
                    List<Assembly> lst = list.Where(x => x.Equals(assembly)).ToList();

                    foreach (var assembly1 in lst)
                    {
                        Type[] assemblyTypes = assembly1.GetTypes();
                        if (assemblyTypes != null)
                        {
                            List<Type> typeList = assemblyTypes.Where(x => x.IsClass && !x.IsAbstract && !x.IsSealed).ToList();
                            foreach (var type in typeList)
                            {
                                Type[] ttypes = type.GetInterfaces();
                                if (ttypes != null)
                                {
                                    var tt = ttypes.FirstOrDefault(x => !x.IsGenericType && list.Contains(x.Assembly));
                                    if (tt != null)
                                    {
                                        container.RegisterType(tt, type);
                                        types.Add(tt, type);
                                    }
                                }
                            }
                        }
                    }

                }
            }
        }
    }
}
